package com.music.common.presentation.actions;

import java.io.File;
import java.io.FileOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import com.music.common.entity.Media;
import com.music.common.errorhandler.PresentationException;
import com.music.common.presentation.forms.UploadForm;
import com.music.common.service.IMediaService;
import com.music.common.service.impl.MediaService;

public class UploadAction extends Action {
	@SuppressWarnings("finally")
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		ActionForward actionForward = mapping.findForward("fail");
		try {
			IMediaService mediaService = new MediaService();
			Integer counter = mediaService.getMediaCounter(request);
			UploadForm uploadForm = (UploadForm) form;
			FormFile myFile = uploadForm.getFile();
			Integer fileCounter = counter + 1;
			// Get the servers upload directory real path name
			String uploadPath = "/songs/";
			String filePath = uploadPath + fileCounter + ".mp3";
			/* Save file on the server */
			System.out.println("File path:" + uploadPath + fileCounter + ".mp3");
			// Create file
			File fileToCreate = new File(uploadPath, fileCounter.toString() + ".mp3");
			// If file does not exists create file
			//if (!fileToCreate.exists()) {
				FileOutputStream fileOutStream = new FileOutputStream(fileToCreate);
				fileOutStream.write(myFile.getFileData());
				fileOutStream.flush();
				fileOutStream.close();
			//}
			File file = new File(filePath);
			Media media = mediaService.getMediaDetailFromFile(file, request);
			// Set file name to the request object
			request.setAttribute("media", media);
			request.setAttribute("fileName", filePath);
			actionForward = (mapping.findForward("success"));
		} catch (Exception ex) {
			throw new PresentationException(ex);
			// System.out.println("Failed at server : \n " +
			// ex.getLocalizedMessage());
		} finally {
			return actionForward;
		}
	}
}
